package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.mapper.AuthorMapper;
import com.heima.article.service.ApArticleService;
import com.heima.article.service.GeneratePageService;
import com.heima.common.exception.CustException;
import com.heima.feigns.AdminFeign;
import com.heima.feigns.WemdiaFeign;
import com.heima.model.admin.pojos.AdChannel;
import com.heima.model.article.dtos.ArticleHomeDTO;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.article.vos.HotArticleVo;
import com.heima.model.common.constants.article.ArticleConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmNews;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

import static com.heima.model.common.constants.article.ArticleConstants.*;


@Service
@Slf4j
//@GlobalTransactional(rollbackFor = Exception.class)
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {

    @Autowired
    GeneratePageService generatePageService;
    @Value("${file.minio.readPath}")
    String readPath;
    @Autowired
    StringRedisTemplate redisTemplate;

    /**
     * 保存或修改文章
     *
     * @param newsId 文章id
     * @return
     */
    @Override
    public void publishArticle(Integer newsId) {
        // 1. 查询并检查自媒体文章  wmNews
        WmNews wmNews = getWmNews(newsId);
        // 2. 封装 ApArticle
        ApArticle apArticle = getApArticle(wmNews);
        // 3. 保存或修改 article信息
        saveOrUpdateArticle(apArticle);
        // 4. 保存关联配置和内容信息
        saveConfigAndContent(wmNews, apArticle);
        // 5.  文章页面静态化
        generatePageService.generateArticlePage(wmNews.getContent(), apArticle);
        // 6. 更新 wmNews状态  改为9  并设置articleId
        updateWmNews(wmNews, apArticle);
        // 7. TODO 通知es索引库添加文章索引
    }

    @Autowired
    private ApArticleMapper apArticleMapper;

    @Value("${file.oss.web-site}")
    private String website;

    /**
     * 根据参数查询文章列表
     *
     * @param loadtype 0为加载更多  1为加载最新
     * @param dto
     * @return
     */
    @Override
    public ResponseResult load(Short loadtype, ArticleHomeDTO dto) {
        // 1.参数校验
        if (loadtype == null || dto == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 2.当类型为加载更多时
        if (!LOADTYPE_LOAD_MORE.equals(loadtype) && !LOADTYPE_LOAD_NEW.equals(loadtype)) {
            loadtype = LOADTYPE_LOAD_MORE;
//            CustException.cust(AppHttpCodeEnum.SERVER_ERROR,"hahahh");
        }

        if (dto.getMaxBehotTime() == null || dto.getMinBehotTime() == null) {
            dto.setMaxBehotTime(new Date());
        }
        if (dto.getMinBehotTime() == null) {
            dto.setMinBehotTime(new Date());
        }
        if (StringUtils.isBlank(dto.getTag())) {
            dto.setTag(DEFAULT_TAG);
        }
        Integer size = dto.getSize();
        if (size == null || size == 0) {
            dto.setSize(10);
        }
        List<ApArticle> apArticles = apArticleMapper.loadArticleList(dto, loadtype);

        for (ApArticle article : apArticles) {
            article.setStaticUrl(readPath + article.getStaticUrl());
        }
        //返回结果
        ResponseResult result = ResponseResult.okResult(apArticles);
        result.setHost(website);
        return result;
    }

    /**
     * 根据参数加载文章列表  v2
     *
     * @param loadType
     * @param dto
     * @param firstPage
     * @return
     */
    @Override
    public ResponseResult load2(Short loadType, ArticleHomeDTO dto, boolean firstPage) {
        if (firstPage) {
            String articleListJson = redisTemplate.opsForValue().get(HOT_ARTICLE_FIRST_PAGE + dto.getTag());
            if (StringUtils.isNotBlank(articleListJson)) {
                List<ApArticle> apArticles = JSON.parseArray(articleListJson, ApArticle.class);
                for (ApArticle apArticle : apArticles) {
                    apArticle.setStaticUrl(readPath + apArticle.getStaticUrl());
                }
                ResponseResult result = ResponseResult.okResult(apArticles);
                result.setHost(website);
                return result;
            }
        }
        return load(loadType, dto);
    }

    /**
     * 更新 wmNews状态  改为9  并设置articleId
     *
     * @param wmNews
     * @param apArticle
     */
    private void updateWmNews(WmNews wmNews, ApArticle apArticle) {
        // 根据文章id查找文章
        Integer wmNewsId = wmNews.getId();
        if (wmNewsId == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "文章id不存在");
        }
        //更新文章
        Long apArticleId = apArticle.getId();
        wmNews.setArticleId(apArticleId);
        wmNews.setStatus(WmNews.Status.PUBLISHED.getCode());
        ResponseResult responseResult = wemediaFeign.updateWmNews(wmNews);
        if (!responseResult.checkCode()) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR, "wemediaFeign远程调用失败");
        }
    }

    /**
     * 保存关联配置和内容信息
     *
     * @param wmNews
     * @param apArticle
     */
    private void saveConfigAndContent(WmNews wmNews, ApArticle apArticle) {
        // 1.参数校验
        if (wmNews == null || apArticle == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 2.保存 文章配置信息
        ApArticleConfig apArticleConfig = new ApArticleConfig();
        apArticleConfig.setArticleId(apArticle.getId());
        apArticleConfig.setIsComment(true);
        apArticleConfig.setIsForward(true);
        apArticleConfig.setIsDelete(false);
        apArticleConfig.setIsDown(false);
        apArticleConfigMapper.insert(apArticleConfig);
        // 3.保存 文章内容信息
        ApArticleContent apArticleContent = new ApArticleContent();
        apArticleContent.setArticleId(apArticle.getId());
        apArticleContent.setContent(wmNews.getContent());
        apArticleContentMapper.insert(apArticleContent);
    }

    @Autowired
    private ApArticleConfigMapper apArticleConfigMapper;
    @Autowired
    private ApArticleContentMapper apArticleContentMapper;

    /**
     * 保存或修改 article信息
     *
     * @param apArticle
     */
    private void saveOrUpdateArticle(ApArticle apArticle) {
        // 1.如果有文章id就修改文章,没有就保存

        if (apArticle.getId() == null) {
            apArticle.setLikes(0);
            apArticle.setCollection(0);
            apArticle.setComment(0);
            apArticle.setViews(0);
            this.save(apArticle);
        } else {
            ApArticle article = getById(apArticle.getId());
            if (article == null) {
                CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "关联的文章不存在");
            }
            this.updateById(apArticle);
            // 删除关联表
            apArticleConfigMapper.delete(Wrappers.<ApArticleConfig>lambdaQuery().eq(ApArticleConfig::getArticleId, apArticle.getId()));
            apArticleContentMapper.delete(Wrappers.<ApArticleContent>lambdaQuery().eq(ApArticleContent::getArticleId, apArticle.getId()));
        }
    }

    @Autowired
    private AuthorMapper authorMapper;
    @Autowired
    private AdminFeign adminFeign;

    /**
     * 封装 ApArticle
     *
     * @param wmNews
     * @return
     */
    private ApArticle getApArticle(WmNews wmNews) {
        ApArticle apArticle = new ApArticle();
        BeanUtils.copyProperties(wmNews, apArticle);
        //根据自媒体用户id查找ap_author
        ApAuthor apAuthor = authorMapper.selectOne(Wrappers.<ApAuthor>lambdaQuery().eq(ApAuthor::getWmUserId, wmNews.getUserId()));
        if (apAuthor == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "作者信息不存在");
        }
        apArticle.setAuthorId(apAuthor.getId().longValue());
        apArticle.setAuthorName(apAuthor.getName());
        // 根据频道id查询频道名称
        Integer channelId = wmNews.getChannelId();
        if (channelId != null) {
            ResponseResult<AdChannel> responseResult = adminFeign.findOne(channelId);
            if (!responseResult.checkCode()) {
                CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR, "adminFeign远程调用失败");
            }
            AdChannel adChannel = responseResult.getData();
            apArticle.setChannelId(channelId);
            apArticle.setChannelName(adChannel.getName());
        }
        // 设置其他字段
        apArticle.setFlag((byte) 0);
        apArticle.setLayout(wmNews.getType());
        return apArticle;
    }

    @Autowired
    private WemdiaFeign wemediaFeign;

    /**
     * 查询并检查自媒体文章  wmNews
     *
     * @param newsId
     * @return
     */
    private WmNews getWmNews(Integer newsId) {
        // 1.参数校验
        if (newsId == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "文章id不能为空");
        }
        // 2.根据id查找文章
        ResponseResult<WmNews> responseResult = wemediaFeign.findWmNewsById(newsId);
        if (!responseResult.checkCode()) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR, "远程调用wemediaFeign失败");
        }
        WmNews wmNews = responseResult.getData();
        // 3.判断该文章状态是否为4或8
        short status = wmNews.getStatus().shortValue();
        if (WmNews.Status.ADMIN_SUCCESS.getCode() != status && WmNews.Status.SUCCESS.getCode() != status) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "当前文章状态不是4或8");
        }

        return wmNews;
    }
}